package cn.com.pxto.commons;

import java.util.*;
import org.apache.log4j.Logger;
import javax.mail.*;
import javax.mail.internet.*;

//�ʼ�������
public class Mailer {
	protected String smtp_server;				//�ʼ�֪ͨ������
	protected String smtp_username;				//�ʼ������ʺ�
	protected String smtp_password;				//�ʼ���������
	
	protected String tcontent;                 //�ʼ�����
	protected String ttitle;                   //�ʼ����⣬������
	protected String tto;                      //�ռ����ʼ���ַ
	protected String BBcc;  					//����
	protected String[] CC=null;                //����
	static Logger logger = Logger.getLogger(Mailer.class);

	 
	public Mailer(String smtp_server,String smtp_username,String smtp_password){
		this.smtp_server=smtp_server;
		this.smtp_username=smtp_username;
		this.smtp_password=smtp_password;
	}
	public void setcontent(String content){
	  this.tcontent=content;
	}
	public void settitle(String title){
	  this.ttitle=title;
	}
	public void setto(String to){
	 this.tto=to;
	}
	public void setCC(String[] cc){
	 this.CC=cc;
	}  
	public boolean Send(){  
		try{        
			sun.misc.BASE64Encoder enc=new sun.misc.BASE64Encoder();
			Properties props=new Properties();     
	        props.put("mail.smtp.host",smtp_server);
	        props.put("mail.smtp.auth","true");
	        Session s=Session.getInstance(props);
	        s.setDebug(true); 
	        MimeMessage message=new MimeMessage(s);
	        InternetAddress from=new InternetAddress(smtp_username);
	        message.setFrom(from);//���÷����� 
	        InternetAddress to=new InternetAddress(tto); 
          
	        message.setRecipient(Message.RecipientType.TO,to);
	        if(null!=BBcc){
	        		InternetAddress Bcc=new InternetAddress(BBcc);
	        			message.setRecipient(Message.RecipientType.BCC,Bcc);  
	        }
	        if(null!=CC){
	        	int adlength=CC.length;
	        	InternetAddress ccAddress=null;
	        	for(int i=0;i<adlength;i++){  
	        			ccAddress=new InternetAddress(CC[i]);
	        			message.setRecipient(Message.RecipientType.CC,ccAddress);            	
	        	}         
          }
          try{
        	  message.setSubject("=?GB2312?B?"+enc.encode(ttitle.getBytes("GB2312"))+"?=");//��������
          }
          catch(Exception e){
          } 
          BodyPart mdp=new MimeBodyPart();
    
          mdp.setContent(tcontent,"text/html;charset=gb2312");//��������
          Multipart mm=new MimeMultipart();
          mm.addBodyPart(mdp);
          message.setContent(mm);
          message.saveChanges();
          Transport transport=s.getTransport("smtp");  
	      transport.connect(smtp_server,smtp_username,smtp_password);//�����֤
          transport.sendMessage(message,message.getAllRecipients());
          transport.close(); 
		}
		catch(MessagingException e){ 
			System.out.println("Mailer.Send() error :"+e);  
			return  false;
		} 	
		return  true;		
	}
}

